package javase.ch06.reflect.myreflectCoustructor;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class MyReflectDemo1 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        /**
         * Class类中用于获取构造方法得方法
         * Constructor<?> [] getConstructors()
         * Constructor<?> [] getDeclaredConstructors()
         * Constructor<T> getConstructor(Class<?>... parameterTypes)
         * Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
         *
         * Costructor类中用于创建对象的方法
         * T newInstance(Object... initargs)
         * setAccessible(boolean flag)
         */

        //1.获取Class字节码文件对象
        Class clazz = Class.forName("reflect.myreflectCoustructor.Student");

        //2.获取public构造方法
        /*Constructor[] constructors1 = clazz.getConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }*/


        //3.获取所有构造方法
        /*Constructor[] constructors2 = clazz.getDeclaredConstructors();
        for (Constructor constructor : constructors2) {
            System.out.println(constructor);
        }*/

        //4.获取指定的构造方法
        Constructor con1 = clazz.getDeclaredConstructor();
        System.out.println(con1);

        Constructor con2 = clazz.getDeclaredConstructor(String.class);
        System.out.println(con2);

        Constructor con3 = clazz.getDeclaredConstructor(int.class);
        System.out.println(con3);

        Constructor con4 = clazz.getDeclaredConstructor(String.class, int.class);
        System.out.println(con4);

        int modifiers = con4.getModifiers();
        System.out.println(modifiers);

        Class[] parameterTypes = con4.getParameterTypes(); //获取参数类型
        for (Class parameterType : parameterTypes) {
            System.out.println(parameterType);
        }

        //暴力反射：表示临时取消权限校验
        con4.setAccessible(true);
        Student student = (Student) con4.newInstance("张三", 18);
        System.out.println(student);

    }
}
